import datetime
from datetime import timedelta
from sqlalchemy.orm import Session

from common.welab_doris import WelabDoris
from app.monitor_doris.models.monitor_doris_custom import MonitorDorisCustom
from app.notice_center.handlers.nc_log_alarm_handler import NCLogAlarmHandler
from app.monitor_doris.handlers.monitor_doris_url_handler import MonitorDorisUrlHandler
from core.logger import logger
from common.utils import CommonTimeUtils

from setting import config


class MonitorDorisCustomHandler():
    """ custom  Handler
    """
    
    def __init__(self):
        self.welab_doris = WelabDoris()
        self.doris_tables = self.get_doris_tables()
    
    
    def get_doris_tables(self):
        doris_tables = [{
            "table": "java_log",
            "log_type": "custom"
        }]
        logger.info(f"doris custom tables:{doris_tables}")
        return doris_tables
    
    
    
    def task_check_custom_handle(self, db: Session):
        # 实际查询是延后1分钟查询历史日志
        delay_min = 1
        now = datetime.datetime.now()
        custom_alarm = []
        
        # 获取所有配置的服务告警策略
        customs_strategy = MonitorDorisCustom.get_all_custom(db)
        for doris_table in self.doris_tables:
            # 从每个表中遍历每个自定义告警策略
            for custom_strategy in customs_strategy:
                # 根据自定义策略查询doris
                cst_begin_time = (now - timedelta(minutes=custom_strategy["interval"]+delay_min)).strftime("%Y-%m-%d %H:%M:%S")
                cst_end_time = (now - timedelta(minutes=delay_min)).strftime("%Y-%m-%d %H:%M:%S")
                result, customs_count = self.welab_doris.get_customs_count(
                                    doris_table["table"],
                                    custom_strategy["log_name"],
                                    custom_strategy["log_level"],
                                    cst_begin_time,
                                    cst_end_time,
                                    custom_strategy["keywords"]
                                )
                if not result:
                    logger.error("doris get customs count failed")
                    return False
                
                # 检查每个服务是否满足自定义策略
                custom_service = []
                for custom_count in customs_count:
                    expr = f"{custom_count['error_count']} {custom_strategy['condition']} {custom_strategy['threshold']}"
                    if not eval(expr):
                        logger.info(f"doris custom_count:{custom_count['fields_app']}=>{custom_count['error_count']} Not satisfied")
                        continue
                    custom_service.append(f"{custom_count['fields_app']}=>{custom_count['error_count']}")
                    
                if len(custom_service) == 0:
                    logger.info(f"doris custom service:{custom_strategy['service_name']} in talbe:{doris_table['table']} is 0, not to alarm")
                    continue
                
                # 添加到告警列表中
                service_info = {
                    "service_name": custom_strategy['service_name'],
                    "log_type": doris_table["log_type"],
                    "error_count": len(custom_service),
                    "cst_begin_time": cst_begin_time,
                    "cst_end_time": cst_end_time,
                    "alarm_threshold": custom_strategy['threshold'],
                    "error_message": " ".join(custom_service)[:400],
                    "app_url": ""
                }
                # 获取青鸾界面的url短连接
                service_info["app_url"] = MonitorDorisUrlHandler().get_custom_short_url(db, doris_table["table"], service_info, custom_strategy)
                
                custom_alarm.append(service_info)
                logger.info(f"doris custom:{custom_strategy['service_name']} require alarm => {service_info}")
            
        # 发送告警信息
        nc_log_alarm_handler = NCLogAlarmHandler()    
        result = nc_log_alarm_handler.post_log_alarm(db, "custom", custom_alarm) 
        if not result:
            logger.info(f"doris custom post_log_alarm failed")
            
        logger.info(f"All doris custom rules have been processed")
        return result
                    
        



def test():
    from common.database import SessionLocal
    session = SessionLocal()
    monitor_doris_custom_handler = MonitorDorisCustomHandler()
    result = monitor_doris_custom_handler.task_check_custom_handle(session)
    print(result)


if __name__ == '__main__':
    test()